package com.teamwings.ctrls.formCtrls;

import com.alibaba.fastjson.JSONObject;
import com.teamwings.common.aspect.annotation.FormControl;
import com.teamwings.common.constant.FormConstant;
import com.teamwings.common.vo.Result;
import com.teamwings.ctrls.Field;
import com.teamwings.ctrls.FormComponent;
import com.teamwings.modules.design.vo.FormVo;
import com.teamwings.modules.page.service.IPageService;
import lombok.Data;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

@FormControl(type = "fn_view_count")
@Data
public class FnViewCount extends FormComponent {

    public FnViewCount() {
        this.type = "fn_view_count";
        this.fieldDefaultLength = "";
        this.fieldType = "INT4";
    }

    // 使用控件调用触发
    @Override
    public Result<?> trigger(FormConstant.TRIGGER_TYPE type, IPageService pageService,
                           FormVo formDesignCode, Object strParam) {
        // 读取数量加一
        Map<String, String> map = new HashMap<>(1);
        JSONObject params = JSONObject.parseObject(strParam + "");
        String formHeadId = params.getString("formHeadId");
        String formId = params.getString("formId");
        String value = params.getString("value");
        String model = params.getString("model");

        if (value == null || value.isEmpty() || value.equals("null")) {
            value = "1";
        }

        value = Integer.valueOf(value) + 1 + "";
        map.put(model, value);
        map.put("ID", formId);

        String tableName = pageService.getTableNameById(formHeadId);
        int num = pageService.update(tableName, map);
        if(num > 0){
            return Result.OK();
        } else {
            return Result.error("");
        }
    }


}
